package com.service;

import static androidx.constraintlayout.widget.ConstraintLayoutStates.TAG;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.baidu.location.demo.MainActivity;
import com.entity.Authority;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import com.microsoft.signalr.OnClosedCallback;
import com.microsoft.signalr.messagepack.MessagePackHubProtocol;

public class HubService extends Service {
    public static HubConnection hubConnection;

    public HubService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Thread chatHubThread=new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                if(MainActivity.friendsListThread!=null)    MainActivity.friendsListThread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(MainActivity.login!=null){
                    try {
                        MainActivity.login.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    hubConnection = HubConnectionBuilder.create("http://101.34.88.150:8080/chatHub")
                            .withHeader("Authorization", Authority.getAuthorization())
                            .withHubProtocol(new MessagePackHubProtocol())
                            .build();
                    hubConnection.onClosed(e -> Log.d(TAG, "Hub异常："+e.getMessage()));
                    hubConnection.start();
                }catch (Exception e){
                    Log.d(TAG, "Hub错误："+e.getMessage());
                }
            }
        };
        chatHubThread.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hubConnection.stop();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}